package com.opener.web.controller;

import com.opener.common.http.HttpResponse;
import com.opener.common.http.StatusCode;
import com.opener.web.spring.exception.AppBaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by baboy on 09/06/2017.
 */
@RestController
@Component
public class ApiContextController extends AppAuthBaseController {
    private Logger logger = LoggerFactory.getLogger(ApiContextController.class);
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public HttpResponse<?> handleRuntimeException(HttpServletRequest request, HttpServletResponse response, Exception exception) {
        exception.printStackTrace();
        HttpResponse httpResponse = new HttpResponse();
        if (exception instanceof AppBaseException){
            AppBaseException e = (AppBaseException) exception;
            httpResponse.setStatus(e.getStatus());
            httpResponse.setMsg(e.getErrorMessage());
        }else{
            httpResponse.setStatus(StatusCode.ERROR);
            httpResponse.setMsg(exception.getLocalizedMessage());
        }
        return httpResponse;

    }
}
